import { Toast } from "antd-mobile";
import { reqlogin } from "../../http/api";

//状态
const initState = {
    //1.初始化
    user: {
        phone: "",
        password: "",
    },
    // 7.1用户信息
    userinfo:sessionStorage.getItem("info")?JSON.parse(sessionStorage.getItem("info")):{},
    pre: "http://localhost:2000",
}

const types = {
    //2.修改user type
    CHANGE_USER: "LOGIN_CHANGE_USER",
    //7.2修改userinfo
    CHANGE_USER_INFO:"LOGIN_CHANGE_USER_INFO"
}

//reducer 修改state
const reducer = (state = initState, action) => {
    switch (action.type) {
        // 3.修改user reducer 
        case types.CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        //7.3修改userinfo
        case types.CHANGE_USER_INFO:
            return{
                ...state,
                userinfo:action.userinfo
            }
            default:
                return state;
    }
}

//actions
export const actions = {
    // 4.修改user action
    changeUser:(key,value)=>({type:types.CHANGE_USER,key,value}),
    //7.4修改userinfo
    changeUserInfo:(userinfo)=>{
        if(userinfo.token){
            //在存仓库一个
            sessionStorage.setItem("info",JSON.stringify(userinfo))
        }else{
            //意味未登录删除
            sessionStorage.removeItem("info")
        }
        return {type:types.CHANGE_USER_INFO,userinfo}
    },
    //6.点了登录按钮
    reqLogin:(push)=>(dispatch,getState)=>{
        let info = getUser(getState())
        reqlogin(info).then(res=>{
            if(res.data.code==200){
                Toast.show({
                    content:res.data.msg,
                })
                //存用户信息
                dispatch(actions.changeUserInfo(res.data.list))
                //跳转页面
                push("/index/home")
            }
        })
    }
}

//selectors
//5.导出user
export const getUser = state=>state.login.user;
//7.5导出userinfo
export const getUserInfo = state=>state.login.userinfo
export const getPre = state => state.login.pre

//导出reducer
export default reducer;